<template>
  <div class="questionnaire_report_return" v-loading="loading">
    <div class="top">
      <div class="search">
        <el-form  label-position="top">
          <el-form-item :label="$t('report.createTime')">
            <el-date-picker size="mini"
              v-model="value4"
              :id="'report_date' + Math.random()"
              type="daterange"
              :picker-options="pickerOptions"
              :placeholder="$t('report.choTimeScope')"
              :editable="boolean"
              align="right">
            </el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('report.tempId')">
            <el-select size="mini" v-model="query.temp_id" @change = "change">
              <el-option
                v-for="item in options"
                :label="item.label"
                :key="item.value"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('report.batchNo')">
            <el-select size="mini" filterable multiple v-model="query.batchNos" :placeholder="$t('report.byBatchNoSearch')">
              <el-option
                v-for="item in options1"
                :label="item.label"
                :key="item.id"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-form  label-position="top" style="margin: 14px 0 34px">
          <el-form-item :label="$t('report.lastUpdateTime')">
            <el-date-picker size="mini"
              v-model="value3"
              :id="'turn' + Math.random()"
              type="daterange"
              :picker-options="pickerOptions"
              :placeholder="$t('report.choTimeScope')"
              :editable="boolean"
              align="right">
            </el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('report.batchRemark')">
            <el-select size="mini" filterable multiple v-model="query.batchRemarks" :placeholder="$t('report.byRatchRemarkSearch')">
              <el-option
                v-for="item in options3"
                :label="item.label"
                :key="item.id"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-button type="primary" class="primary_btn fr find" @click="search">{{$t('public.search2')}}</el-button>
        </el-form>
      </div>
      <affix :label="$t('report.statusReport')"></affix>
    </div>
    <div :id = "id">
      <el-row class="ichars">
          <highcharts :options="highchartsOptions"></highcharts>
      </el-row>
      <el-row class="ichars">
          <highcharts :options="highchartsOptionsCi"></highcharts>
          <div class="notes">
            <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
            <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
          </div>
      </el-row>
      <div class="tab">
        <div class="export">

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            @click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click="exportPdf">{{$t('report.exportPDF')}}</el-button>
        </div>
        <report-table :data="tableData" :sum="totalData" :config="config"></report-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import {exportReportPdf, colorConfigArr} from '@/utils/reportUtils.js'
  import reportTable from '../base/reportTable.vue'
  import {getDateTime, deepClone} from '@/utils/m7Utils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  import {headOptionsToXlsxHeaders} from 'src/utils/reportUtils.js'
  export default {
    name: 'questionnaire_report_return',
    data () {
      return {
        loading: false,
        options: [],
        query: {
          reportType: 'questionnaire_report_return',
          temp_id: '',
          batchNos: [],
          batchRemarks: [],
          create_time_begin: '',
          create_time_end: '',
          return_time_begin: '',
          return_time_end: ''
        },
        dialogVisible: false,
        batchNumber: [],
        batchInstructions: [],
        tableDatas: [],
        tableDataCon: [],
        config: [{
          displayname: this.$t('report.visitStatus'),
          name: 'returnState',
          show: true
        }, {
          displayname: this.$t('report.count'),
          name: 'count',
          show: true
        },
        {
          displayname: this.$t('report.accountingFor'),
          name: 'AccountingFor',
          show: true,
          timeType: 'percent'
        }],
        id: 'questionnaire_report_return',
        value3: '',
        value4: '',
        boolean: false,
        pickerOptions: {
          shortcuts: [{
            text: this.$t('sms.thisOneWeek'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisOneMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisThreeMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        serveNumData: [],
        highchartsDefaultOptions: {
          chart: {
            type: 'column',
            animation: false
          },
          colors: colorConfigArr,
          xAxis: {
            categories: []
          },
          legend: {
            enabled: false
          },
          yAxis: {
            title: {
              text: this.$t('report.count')
            }
          },
          title: {
            text: this.$t('report.visitStatusCol')
          },
          plotOptions: {
            series: {
              borderWidth: 0,
              dataLabels: {
                enabled: true,
                format: '{point.y}'
              }
            }
          },
          tooltip: {
            headerFormat: '',
            pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y}',
            shared: true
          },

          credits: {enabled: false},
          series: []
        },
        highchartsDefaultOptionsC: {
          chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false
          },
          colors: colorConfigArr,
          title: { text: this.$t('report.visitStatusPie') },
          tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
          },
          plotOptions: {
            pie: {
              allowPointSelect: true,
              cursor: 'pointer',
              dataLabels: {
                enabled: true,
                format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                style: {}
              },
              showInLegend: true
            }
          },
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      affix,
      reportTable
    },
    methods: {
      getTotalData (tableDataCon) {
        if (!tableDataCon || tableDataCon.length === 0) {
          return [{'returnState': this.$t('report.total')}]
        }
        let sum = {'returnState': this.$t('report.total'), 'count': tableDataCon[0]._totalResult, 'AccountingFor': '100%'}
        return [sum]
      },
      getTableData (tableDatas, tableDataCon) {
        if (!tableDataCon || tableDataCon.length === 0) {
          return []
        }
        let tabD = []
        let accountSum = tableDataCon[0]._totalResult
        for (let i = 0; i < tableDatas.length; i++) {
          tabD.push({
            'returnState': tableDatas[i].displayname,
            'count': tableDataCon[0][tableDatas[i].name],
            'AccountingFor': (tableDataCon[0][tableDatas[i].name] / accountSum * 100).toFixed(1) + '%'
          })
        }
        return tabD
      },
      getSearchQueryData () {
        // 初始化查询时间
        if (this.value4) {
          let time = getDateTime(this.value4[0]).split(' ')
          let timeEnd = getDateTime(this.value4[1]).split(' ')
          this.query.create_time_begin = time[0]
          this.query.create_time_end = timeEnd[0]
        } else {
          this.query.create_time_begin = ''
          this.query.create_time_end = ''
        }
        if (this.value3) {
          let time1 = getDateTime(this.value3[0]).split(' ')
          let timeEnd1 = getDateTime(this.value3[1]).split(' ')
          this.query.return_time_begin = time1[0]
          this.query.return_time_end = timeEnd1[0]
        } else {
          this.query.return_time_begin = ''
          this.query.return_time_end = ''
        }
        // 查询条件
        let data = {
          account: this.$store.state.session.user.account,
          query: this.query
        }
        return data
      },
      search () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        this.loading = true
        // 查询数据
        this.$store.dispatch('queryQuesResultReport', data).then((res) => {
          this.loading = false
          this.tableDatas = deepClone(res.tableHeader.Config) || []
          this.tableDataCon = deepClone(res.data) || []
        })
      },
      exportXlsx () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        this.loading = true
        // 查询数据
        this.$store.dispatch('queryQuesResultReport', data).then((res) => {
          this.loading = false
          var tableDatas = deepClone(res.tableHeader.Config) || []
          var tableDataCon = deepClone(res.data) || []
          var config = deepClone(this.config)
          var sum = this.getTotalData(tableDataCon)
          var tableData = this.getTableData(tableDatas, tableDataCon).concat(sum)

          var headers = headOptionsToXlsxHeaders(config)

          var dh = XlsxUtil.getDownloadHelper(headers, tableData, true)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.statusReport') + timeStamp)
        })
      },
      change () {
        this.query.batchNos = []
        this.query.batchRemarks = []
      },
      close () {
        this.isShow = false
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.statusReport'), id: this.id})
      },
      exportXls () {
        let data = {
          Method: 'exportQuesResultReport',
          Query: {
            reportType: 'questionnaire_report_return',
            temp_id: this.query.temp_id,
            batchNos: this.query.batchNos,
            batchRemarks: this.query.batchRemarks,
            create_time_begin: '',
            create_time_end: '',
            return_time_begin: '',
            return_time_end: '',
            account: this.$store.state.session.user.account
          }
        }
        // 初始化查询时间
        if (this.value4) {
          let time = getDateTime(this.value4[0]).split(' ')
          let timeEnd = getDateTime(this.value4[1]).split(' ')
          data.Query.create_time_begin = time[0]
          data.Query.create_time_end = timeEnd[0]
        } else {
          data.Query.create_time_begin = ''
          data.Query.create_time_end = ''
        }
        if (this.value3) {
          let time1 = getDateTime(this.value3[0]).split(' ')
          let timeEnd1 = getDateTime(this.value3[1]).split(' ')
          data.Query.return_time_begin = time1[0]
          data.Query.return_time_end = timeEnd1[0]
        } else {
          data.Query.return_time_begin = ''
          data.Query.return_time_end = ''
        }
        this.$store.dispatch('exportQuesResultReport', data)
      }
    },
    computed: {
      highchartsOptions () {
        let hOptions = deepClone(this.highchartsDefaultOptions)
        if (!this.tableDataCon || this.tableDataCon.length === 0) {
          return hOptions
        }
        let categoriesArray = []
        let seriesArray = [{
          name: ' ',
          colorByPoint: true,
          data: []
        }]
        for (let i = 0; i < this.tableDatas.length; i++) {
          categoriesArray.push(this.tableDatas[i].displayname)
        }
        hOptions.xAxis.categories = categoriesArray
        for (let i = 0; i < this.tableDatas.length; i++) {
          seriesArray[0].data.push({
            name: this.tableDatas[i].displayname,
            y: this.tableDataCon[0][this.tableDatas[i].name]
          })
        }
        hOptions.series = seriesArray
        return hOptions
      },
      highchartsOptionsCi () {
        let hOptionsC = deepClone(this.highchartsDefaultOptionsC)
        if (!this.tableDataCon || this.tableDataCon.length === 0) {
          return hOptionsC
        }
        let seriesArray = [{
          type: 'pie',
          name: this.$t('report.percentage'),
          data: []
        }]
        for (let i = 0; i < this.tableDatas.length; i++) {
          seriesArray[0].data.push([
            `${this.tableDatas[i].displayname}(${this.tableDataCon[0][this.tableDatas[i].name]})`,
            this.tableDataCon[0][this.tableDatas[i].name]
          ])
        }
        hOptionsC.series = seriesArray
        return hOptionsC
      },
      totalData () {
        return this.getTotalData(this.tableDataCon)
      },
      tableData () {
        return this.getTableData(this.tableDatas, this.tableDataCon)
      },
      // 批次号
      options1 () {
        let batchNo = []
        for (let b = 0; b < this.batchNumber.length; b++) {
          if (this.query.temp_id === this.batchNumber[b].dbType) {
            batchNo.push(this.batchNumber[b])
          }
        }
        return batchNo.map(batch => ({ label: batch.batchNo, value: batch.batchNo, id: batch._id }))
      },
      // 批次说明列表
      options3 () {
        let batchNo = []
        for (let b = 0; b < this.batchInstructions.length; b++) {
          if (this.query.temp_id === this.batchInstructions[b].dbType) {
            batchNo.push(this.batchInstructions[b])
          }
        }
        return batchNo.map(batch => ({ label: batch.batchRemark, value: batch.batchRemark, id: batch._id }))
      }
    },
    beforeMount () {
      // 按批次号搜索
      this.$store.dispatch('getCache', {type: 'getQuestionnaireImportBatchNo'}).then(agents => {
        this.batchNumber = deepClone(agents) || this.batchNumber
      })
      // 按批次说明搜索
      this.$store.dispatch('getCache', {type: 'getQuestionnaireImportBatchRemark'}).then(agents => {
        this.batchInstructions = deepClone(agents) || this.batchInstructions
      })
      // 模板搜索
      this.$store.dispatch('getCache', {type: 'questionnaireTemp'}).then(agents => {
        this.options = agents.map(agent => ({ label: agent.name, value: agent._id }))
        this.query.temp_id = agents[0]._id
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .questionnaire_report_return
    .export
      .pdf
        margin 0px
    .search
      .el-form
        padding-left 18px
        .primary_btn
          margin-top 16px
      .el-form-item
        display: inline-block
        margin: 0 16px 0 0
        vertical-align top
</style>
